import React, { useState, useEffect } from 'react';
import './MyPage.css';
import { useLocation, useParams } from 'react-router-dom';
import MyFavorites from '../components/mypage/MyFavorites'; 
import MyFollowers from '../components/mypage/MyFollowers'; 
import MyFollowing from '../components/mypage/MyFollowing'; 
import MyLikes from '../components/mypage/MyLikes'; 
import MypageCategory from '../components/mypage/MypageCategory'; 

const MyPage = () => {
  const location = useLocation();
  const query = new URLSearchParams(location.search).get('query') || '1';  // 获取 query 参数，默认值为 '1'
  const [category, setCategory] = useState('topics');  // 默认类别为 'topics'
  const [results, setResults] = useState([]);

  // 根据路径更新 category
  useEffect(() => {
    const pathSegments = location.pathname.split('/');
    const currentCategory = pathSegments[pathSegments.length - 2]; // 获取倒数第二个部分作为 category
    if (['following', 'followers', 'likes', 'topics'].includes(currentCategory)) {
      setCategory(currentCategory); // 只有这些合法的 category 才进行设置
    } else {
      setCategory('topics'); // 默认分类为话题
    }
  }, [location]);

  // 根据 category 更新结果
  useEffect(() => {
    if (!query) return;

    const fetchResults = () => {
      let fetchedResults = [];
      switch (category) {
        case 'topics':
          fetchedResults = [`话题1: ${query}`, `话题2: ${query}`, `话题3: ${query}`];
          break;
        case 'likes':
          fetchedResults = [`帖子1: ${query}`, `帖子2: ${query}`, `帖子3: ${query}`];
          break;
        case 'followers':
          fetchedResults = [`粉丝1: ${query}`, `粉丝2: ${query}`, `粉丝3: ${query}`];
          break;
        case 'following':
          fetchedResults = [`关注1: ${query}`, `关注2: ${query}`, `关注3: ${query}`];
          break;
        default:
          fetchedResults = [`话题1: ${query}`, `话题2: ${query}`, `话题3: ${query}`];
      }
      setResults(fetchedResults); // 更新 results
    };

    fetchResults();  // 根据 category 更新结果
  }, [query, category]);  // 只依赖 query 和 category

  // 渲染相应的组件
  const renderResults = () => {
    switch (category) {
      case 'topics':
        return <MyFavorites query={query} results={results} />;
      case 'likes':
        return <MyLikes query={query} results={results} />;
      case 'followers':
        return <MyFollowers query={query} results={results} />;
      case 'following':
        return <MyFollowing query={query} results={results} />;
      default:
        return <MyFavorites query={query} results={results} />;
    }
  };

  return (
    <div className='mypage'>
      <MypageCategory category={category} onCategoryChange={setCategory} />
      <div className='mypage-right'>
        {query ? (
          <>
            {renderResults()}  {/* 根据选中的类别渲染相应的组件 */}
          </>
        ) : (
          <p>暂无内容</p>
        )}
      </div>
    </div>
  );
};

export default MyPage;
